package org.example.ftp.ftpservice;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.InputStream;

public class FtpUtil {
    // ftp 服务器ip地址
    private static final String FTP_ADDRESS = "192.168.3.253";
    // 端口号
    private static final int FTP_PORT = 21;
    // 用户名
    private static final String FTP_USERNAME = "user-file";
    // 密码
    private static final String FTP_PASSWORD = "abc...94145";
    // 附件路径
    private static final String FTP_BASEPATH = "/home/user-file/files";

    public static boolean uploadFile(String fileName, InputStream input) {
        boolean success = false;
        FTPClient ftp = new FTPClient();
        try{
            int reply;
            ftp.connect(FTP_ADDRESS,FTP_PORT); // 连接ftp服务器
            ftp.login(FTP_USERNAME,FTP_PASSWORD); // 登录
            reply = ftp.getReplyCode();
            if(!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return false;
            }
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftp.makeDirectory(FTP_BASEPATH);
            ftp.changeWorkingDirectory(FTP_BASEPATH);
            ftp.enterLocalPassiveMode();
            ftp.storeFile(fileName,input);
            input.close();
            ftp.logout();
            success = true;
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(ftp.isConnected()) {
                try{
                    ftp.disconnect();
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return success;
    }
}
